#version 430 core
out vec4 FragColor;

in vec3 v2f_Normal;
in vec3 v2f_FragPosInWorldSpace;

uniform mat4 u_LightViewMatrix;
uniform sampler2D u_FrontDepthTexture;
uniform sampler2D u_BackDepthTexture;
uniform vec3 u_LightPos;
uniform float u_NearPlane;
uniform float u_FarPlane;

void main()
{
	vec3 Color = vec3(1.0f);
	vec3 Normal = normalize(v2f_Normal);

	vec3 LightColor = vec3(0.3f);

	// Ambient
	vec3 Ambient = 0.3f * Color;
	// Diffuse
	vec3 LightDir = normalize(u_LightPos - v2f_FragPosInWorldSpace);
	float Diff = max(dot(LightDir, Normal), 0);
	vec3 Diffuse = Diff * LightColor;

	// Shadow
    float Shadow = 0.0f;
	vec3 PositionInLightSpace = (u_LightViewMatrix * vec4(v2f_FragPosInWorldSpace, 1.0f)).xyz;
	float Length = length(PositionInLightSpace);
	PositionInLightSpace /= Length;
	float CurrentDepth = (Length - u_NearPlane) / (u_FarPlane - u_NearPlane);
	float ClosestDepth;
	if(PositionInLightSpace.z >= 0.0f)
	{
		vec2 TexCoord;
		TexCoord.x = (PositionInLightSpace.x / (1.0f + PositionInLightSpace.z)) * 0.5f + 0.5f;
		TexCoord.y = (PositionInLightSpace.y / (1.0f + PositionInLightSpace.z)) * 0.5f + 0.5f;

		ClosestDepth = texture(u_FrontDepthTexture, TexCoord).r;
	}
	else
	{
		vec2 TexCoord;
		TexCoord.x = (PositionInLightSpace.x / (1.0f - PositionInLightSpace.z)) * 0.5f + 0.5f;
		TexCoord.y = (PositionInLightSpace.y / (1.0f - PositionInLightSpace.z)) * 0.5f + 0.5f;

		ClosestDepth = texture(u_BackDepthTexture, TexCoord).r;
	}
	if(CurrentDepth - 0.005 > ClosestDepth)
		Shadow = 1.0f;

	vec3 Lighting = (Ambient + (1.0f - Shadow) * Diffuse) * Color;
	FragColor = vec4(Lighting, 1.0f);
}